<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchNoticesAPI } from '@/apis/fetchNotices'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<Notice>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Notice>): Promise<LoadMoreData<Notice>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchNoticesAPI(
    { page: _page.toString(), limit: '10' },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

function handleTapNotice(id: string) {
  router.push({
    name: 'noticeDetail',
    params: { id },
  })
}
</script>

<template>
  <Spacer height="40" />
  <view
    v-for="item in dataList"
    :key="item.id"
    class="mb-24rpx rounded-20rpx bg-white p-24rpx"
    @tap="handleTapNotice(item.id.toString())"
  >
    <view class="text-32rpx text-#333333 font-semibold leading-45rpx">
      {{ item.title }}
    </view>
    <Spacer height="16" />
    <view class="max-h-80rpx overflow-hidden text-28rpx text-#848484 leading-40rpx">
      {{ item.introduce }}
    </view>
    <Spacer height="24" />
    <view class="text-24rpx text-#333333 leading-32rpx">
      发布时间：{{ item.create_time }}
    </view>
  </view>
  <!-- 加载更多 -->
  <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
  <Spacer height="240" />
  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'notice'
style:
  navigationBarTitleText: '公告'
</route>
